﻿using System.Configuration;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace GearOptimizer.Adapters
{
    public class MongoRepository<T> : IRepository<T> where T : IIdentifiable
    {
        private readonly string serverName;
        private readonly string databaseName;
        private readonly string userName;
        private readonly string password;

        public MongoRepository(string serverName, string databaseName, string userName = null, string password = null)
        {
            this.serverName = serverName;
            this.databaseName = databaseName;
            this.userName = userName;
            this.password = password;
        }

        private MongoCollection<T> GetMongoCollection()
        {

            var connectionString = "mongodb://" + userName + ":" +
                                   password + "@" +
                                   serverName + "?safe=true";
            var server = MongoServer.Create(connectionString);
            var database = server.GetDatabase(databaseName);
            var collection = database.GetCollection<T>(typeof(T).Name);
            return collection;
        }

        public T Get(string id)
        {
            var collection = GetMongoCollection();
            return collection.FindOne(Query<T>.EQ(x => x.Id, id));
        }

        public void Set(T value)
        {
            var collection = GetMongoCollection();
            collection.Save(value);
        }

        public void Remove(string id)
        {
            var collection = GetMongoCollection();
            collection.Remove(Query<T>.EQ(x => x.Id, id));
        }

        public bool Contains(string id)
        {
            var collection = GetMongoCollection();
            return collection.FindOne(Query<T>.EQ(x => x.Id, id)) != null;
        }
    }
}